import { select, put, call } from 'redux-saga/effects';
import { LOGIN_ING, LOGIN_SUC, LOGIN_FAIL } from '../store/user'

import { fetchData } from '../utils/axios';

function initalLogin(data) {
    localStorage.setItem('logged', true);
    localStorage.setItem('userInfo', JSON.stringify(data.userInfo)); //需要保存下次可以获取token的数据
}
function clearLogin() {
    localStorage.removeItem('logged');
    localStorage.removeItem('userInfo');
}

export function* login(data) {
    try {
        yield put({ type: LOGIN_ING })
        const res = yield call(fetchData, { params: data, api: 'login' });
        console.log(res)
        if (res.code == 0) {
            initalLogin(res.data)
            yield put({ type: LOGIN_SUC, data: res.data })
        } else {
            clearLogin();
            yield put({ type: LOGIN_FAIL })
        }
    } catch (e) {
        clearLogin()
        yield put({ type: LOGIN_FAIL })
    }
}
// function* authorize(user,password){
//     try {
//         const token = yield call(Api.authorize, user, password)
//         yield put({type: 'LOGIN_SUCCESS', token})
//         return token
//       } catch(error) {
//         yield put({type: 'LOGIN_ERROR', error})
//       }
// }

// function* loginFlow(){
//     while(true){
//         const {user,password} = yield take('LOGIN_REQUEST')
//         const token = yield call(authorize,user,password)
//         if(token){
//             yield take('LOGOUT')
//             yield call(loginout)
//         }
//     }
// }